<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>后端连接测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .test-section {
            margin: 20px 0;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .success { color: #28a745; }
        .error { color: #dc3545; }
        .warning { color: #ffc107; }
        .info { color: #17a2b8; }
        button {
            background: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover { background: #0056b3; }
        button:disabled { background: #6c757d; cursor: not-allowed; }
        .log {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            padding: 10px;
            margin: 10px 0;
            font-family: monospace;
            white-space: pre-wrap;
            max-height: 300px;
            overflow-y: auto;
        }
        input {
            padding: 8px;
            margin: 5px;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 200px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔍 后端连接诊断工具</h1>
        
        <div class="test-section">
            <h3>1. 基础连接测试</h3>
            <button onclick="testBasicConnection()">测试后端连接</button>
            <div id="basicResult" class="log"></div>
        </div>

        <div class="test-section">
            <h3>2. 登录接口测试</h3>
            <div>
                <input type="text" id="username" placeholder="用户名" value="admin">
                <input type="password" id="password" placeholder="密码" value="admin123">
                <button onclick="testLogin()">测试登录</button>
            </div>
            <div id="loginResult" class="log"></div>
        </div>

        <div class="test-section">
            <h3>3. 工单接口测试</h3>
            <button onclick="testTicketsAPI()">测试工单列表</button>
            <div id="ticketsResult" class="log"></div>
        </div>

        <div class="test-section">
            <h3>4. 网络诊断</h3>
            <button onclick="runNetworkDiagnostics()">运行网络诊断</button>
            <div id="networkResult" class="log"></div>
        </div>

        <div class="test-section">
            <h3>5. 常见问题检查</h3>
            <button onclick="checkCommonIssues()">检查常见问题</button>
            <div id="issuesResult" class="log"></div>
        </div>
    </div>

    <script>
        const API_BASE_URL = 'http://localhost:8080/api';
        
        function log(elementId, message, type = 'info') {
            const element = document.getElementById(elementId);
            const timestamp = new Date().toLocaleTimeString();
            const className = type === 'error' ? 'error' : type === 'success' ? 'success' : type === 'warning' ? 'warning' : 'info';
            element.innerHTML += `<span class="${className}">[${timestamp}] ${message}</span>\n`;
            element.scrollTop = element.scrollHeight;
        }

        function clearLog(elementId) {
            document.getElementById(elementId).innerHTML = '';
        }

        async function testBasicConnection() {
            clearLog('basicResult');
            log('basicResult', '开始测试后端基础连接...', 'info');
            
            try {
                // 测试根路径
                const response = await fetch('http://localhost:8080/', {
                    method: 'GET',
                    mode: 'cors'
                });
                
                if (response.ok) {
                    log('basicResult', '✅ 后端服务运行正常', 'success');
                    log('basicResult', `状态码: ${response.status}`, 'info');
                } else {
                    log('basicResult', `⚠️ 后端响应异常: ${response.status}`, 'warning');
                }
            } catch (error) {
                log('basicResult', `❌ 连接失败: ${error.message}`, 'error');
                
                if (error.message.includes('Failed to fetch')) {
                    log('basicResult', '可能原因:', 'warning');
                    log('basicResult', '1. 后端服务未启动', 'warning');
                    log('basicResult', '2. 端口8080被占用', 'warning');
                    log('basicResult', '3. CORS配置问题', 'warning');
                }
            }
        }

        async function testLogin() {
            clearLog('loginResult');
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            
            log('loginResult', `测试登录: ${username}`, 'info');
            
            try {
                const response = await fetch(`${API_BASE_URL}/auth/login`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ username, password }),
                    mode: 'cors'
                });

                log('loginResult', `响应状态: ${response.status}`, 'info');
                
                const data = await response.json();
                log('loginResult', `响应数据: ${JSON.stringify(data, null, 2)}`, 'info');
                
                if (response.ok && data.success) {
                    log('loginResult', '✅ 登录成功', 'success');
                    log('loginResult', `Token: ${data.data?.token?.substring(0, 20)}...`, 'info');
                } else {
                    log('loginResult', `❌ 登录失败: ${data.message || '未知错误'}`, 'error');
                }
            } catch (error) {
                log('loginResult', `❌ 请求失败: ${error.message}`, 'error');
                
                if (error.message.includes('CORS')) {
                    log('loginResult', 'CORS错误 - 后端需要配置CORS', 'error');
                }
            }
        }

        async function testTicketsAPI() {
            clearLog('ticketsResult');
            log('ticketsResult', '测试工单列表接口...', 'info');
            
            try {
                const response = await fetch(`${API_BASE_URL}/tickets`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    mode: 'cors'
                });

                log('ticketsResult', `响应状态: ${response.status}`, 'info');
                
                if (response.status === 401) {
                    log('ticketsResult', '⚠️ 需要认证 - 这是正常的', 'warning');
                    log('ticketsResult', '请先登录获取Token', 'info');
                } else {
                    const data = await response.json();
                    log('ticketsResult', `响应数据: ${JSON.stringify(data, null, 2)}`, 'info');
                }
            } catch (error) {
                log('ticketsResult', `❌ 请求失败: ${error.message}`, 'error');
            }
        }

        async function runNetworkDiagnostics() {
            clearLog('networkResult');
            log('networkResult', '开始网络诊断...', 'info');
            
            // 检查端口是否开放
            const ports = [8080, 3000, 8081];
            for (const port of ports) {
                try {
                    const response = await fetch(`http://localhost:${port}/`, {
                        method: 'HEAD',
                        mode: 'no-cors'
                    });
                    log('networkResult', `✅ 端口 ${port} 可访问`, 'success');
                } catch (error) {
                    log('networkResult', `❌ 端口 ${port} 不可访问`, 'error');
                }
            }
            
            // 检查DNS解析
            try {
                const response = await fetch('http://localhost:8080/api/health', {
                    method: 'GET',
                    mode: 'cors'
                });
                log('networkResult', '✅ DNS解析正常', 'success');
            } catch (error) {
                log('networkResult', '❌ DNS解析可能有问题', 'error');
            }
        }

        function checkCommonIssues() {
            clearLog('issuesResult');
            log('issuesResult', '检查常见问题...', 'info');
            
            // 检查浏览器控制台
            log('issuesResult', '1. 检查浏览器控制台是否有错误', 'info');
            log('issuesResult', '2. 检查后端服务是否启动', 'info');
            log('issuesResult', '3. 检查端口8080是否被占用', 'info');
            log('issuesResult', '4. 检查CORS配置', 'info');
            log('issuesResult', '5. 检查数据库连接', 'info');
            log('issuesResult', '6. 检查JWT配置', 'info');
            
            // 提供解决方案
            log('issuesResult', '\n解决方案:', 'warning');
            log('issuesResult', '1. 启动后端: mvn spring-boot:run', 'info');
            log('issuesResult', '2. 检查application.yml配置', 'info');
            log('issuesResult', '3. 检查数据库连接字符串', 'info');
            log('issuesResult', '4. 检查用户表是否有测试数据', 'info');
            log('issuesResult', '5. 检查密码加密方式', 'info');
        }

        // 页面加载时自动运行基础测试
        window.onload = function() {
            testBasicConnection();
        };
    </script>
</body>
</html>
